package singsong;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class SongFileReader {
	
	public Song read(File file) throws IOException {
		Song song = new Song();
		BufferedReader reader = new BufferedReader(new FileReader(file));
		String line;
		while ((line = reader.readLine()) != null) {
			if (line.trim().isEmpty()) {
				continue;
			}
			String[] values = line.split(",");
			if (values.length != 3) {
				System.err.println("Error in file: " + file.getAbsolutePath());
				break;
			}
			String name = values[0].trim();
			String instrument = values[1].trim();
			String trackFilename = values[2].trim();
			TrackData data = readTrackDataFile(new File(file.getParent(), trackFilename));
			Track track = new Track(instrument, data);
			track.setName(name);
			song.getTracks().add(track);
		}
		return song;
	}
	
	public TrackData readTrackDataFile(File file) throws IOException {
		TrackData data = null;
		BufferedReader reader = new BufferedReader(new FileReader(file));
		String line;
		while ((line = reader.readLine()) != null) {
			if (line.trim().isEmpty()) {
				continue;
			}
			if (data == null) {
				float sampleRate = Float.parseFloat(line.trim());
				data = new TrackData(sampleRate);
			} else {
				String[] values = line.split(",");
				if (values.length != 2) {
					System.err.println("Error in file: " + file.getAbsolutePath());
					break;
				}
				float frequency = Float.parseFloat(values[0].trim());
				float volume = Float.parseFloat(values[1].trim());
				data.addSample(frequency, volume);
			}
		}
		return data;
	}
}
